/*
 * @Author: qinuoyun
 * @Date:   2019-11-01 10:47:39
 * @Last Modified by:   qinuoyun
 * @Last Modified time: 2019-11-20 14:50:59
 */
import Vue from 'vue'

import importModel from '../plugins/import-model'

import importGather from '../plugins/import-gather'

import createAction from '../plugins/create-action'

// 添加图层
import importLayers from '../plugins/import-layers'
// 创建模型
import createModel from '../plugins/create-model'

// 新建页面
import createPages from '../plugins/create-page'




const drive = {
  "model": Vue.extend(importModel),
  "create": Vue.extend(createModel),
  "gather": Vue.extend(importGather),
  "layers": Vue.extend(importLayers),
  "action": Vue.extend(createAction),
  "newpage": Vue.extend(createPages)
}

/**
 * 事件绑定
 * @param {any} element  绑定dom
 * @param {any} event    事件类型
 * @param {any} listener 方法
 */
function addEvent(element, event, listener) {
  if (element.addEventListener) {
    element.addEventListener(event, listener, false);
  } else if (element.attachEvent) {
    element.attachEvent('on' + event, listener);
  } else {
    element['on' + event] = listener;
  }
}


let getAnInstance = (data, type) => {
  //用于处理VUECX
  let $parent = vm.$parent;
  let $store = vm.$store;
  let instance = new drive[type]({
    propsData: {
      value: data
    },
    el: document.createElement('div')
  })
  instance.$parent = $parent;
  instance.$store = $store;
  return instance;
}

let pool = {};

let vm = null

let directives = {

  dialog: {
    bind: function(el, binding, vnode) { //被绑定
      if(vm == null){
        vm = vnode.context;
      }
    },
    update: function(el, binding, vnode) { //组件更新
      let type = el.dataset.type;
      pool[type] = binding.value;
    },
    // 指令的定义
    inserted: function(el, binding, vnode) {
      let type = el.dataset.type;
      if (!pool[type]) {
        pool[type] = binding.value;
      }
      addEvent(el, 'click', function() {
        // let root  =  document.getElementsByTagName('body')[0];
        let data = pool[type];
        let instance = getAnInstance(data, type)
        let model = vm.$el.appendChild(instance.$el);
        instance.dialogVisible = true;
        instance.$watch('dialogVisible', function() {
          instance.dialogVisible = false;
          // vm.$el.removeChild(model)
        });
      });
    }
  }
}

export default directives;
